package com.kgc.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.kgc.pojo.Role;
import com.kgc.pojo.User;
import com.kgc.service.RoleService;
import com.kgc.service.UserService;

@Controller
@RequestMapping(value = {"/user", "/u"})
public class UserController
{
    private Logger logger = Logger.getLogger(UserController.class);
    
    @Resource
    UserService userService;
    
    @Resource
    RoleService roleService;
    
    /**
     * 跳转到主页 <一句话功能简述> <功能详细描述>
     * 
     * @return
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("dologin.html")
    public String dologin(HttpSession session, User user)
        throws Exception
    {
        User u = userService.selectUserByCodeAndPassword(user);
        session.setAttribute("userSession", u);
        return "frame";
    }
    
    /**
     * 
     * <一句话功能简述> <功能详细描述>
     * 
     * @param userCode
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("user.do")
    public @ResponseBody User isExist(String userCode)
    {
        List<User> list = userService.selectUserByCode(userCode);
        User u = null;
        if (!(list == null || list.isEmpty()))
        {
            u = list.get(0);
            u.setUserCode("exist");
            return u;
        }
        return new User();
    }
    
    @RequestMapping("{myname}/user1.do")
    public @ResponseBody User isExist1(@PathVariable(value = "myname") String userCode)
    {
        List<User> list = userService.selectUserByCode(userCode);
        User u = null;
        if (!(list == null || list.isEmpty()))
        {
            u = list.get(0);
            u.setUserCode("exist");
            return u;
        }
        return new User();
    }
    
    @RequestMapping("useraddsave2.html")
    public String userAdd2(User user, HttpServletRequest request,
        @RequestParam(value = "attachs", required = false) MultipartFile[] attachs)
    {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("uploadFile path ============== > " + path);
        for (int i = 0; i < attachs.length; i++)
        {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty())
            {
                if (i == 0)
                {
                    errorInfo = "uploadFileError";
                }
                else if (i == 1)
                {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();// 原文件名
                logger.info("uploadFile oldFileName ============== > " + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀
                logger.debug("uploadFile prefix============> " + prefix);
                int filesize = 500000;
                logger.debug("uploadFile size============> " + attach.getSize());
                if (attach.getSize() > filesize)
                {// 上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                }
                else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg"))
                {// 上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextLong() + "_Personal.jpg";
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists())
                    {
                        targetFile.mkdirs();
                    }
                    // 保存
                    try
                    {
                        attach.transferTo(targetFile);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0)
                    {
                        idPicPath = path + File.separator + fileName;
                    }
                    else if (i == 1)
                    {
                        workPicPath = path + File.separator + fileName;
                    }
                    logger.debug("idPicPath: " + idPicPath);
                    logger.debug("workPicPath: " + workPicPath);
                    
                }
                else
                {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        
        return "userlist";
    }
    
    @RequestMapping("useraddsave.html")
    public String userAdd(User user, HttpServletRequest request,
        @RequestParam(value = "a_idPicPath", required = false) MultipartFile attach)
    {
        String idPicPath = null;
        // 判断文件是否为空
        if (!attach.isEmpty())
        {
            String path =
                request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            
            String oldFileName = attach.getOriginalFilename();// 原文件名
            String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀
            int filesize = 500000;
            
            if (attach.getSize() > filesize)
            {// 上传大小不得超过 500k
                request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
                return "useradd";
            }
            else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg")
                || prefix.equalsIgnoreCase("pneg"))
            {
                // 上传图片格式不正确
                String fileName = System.currentTimeMillis() + RandomUtils.nextLong() + "_Personal.jpg";
                logger.debug("new fileName======== " + attach.getName());
                File targetFile = new File(path, fileName);
                if (!targetFile.exists())
                {
                    targetFile.mkdirs();
                }
                // 保存
                try
                {
                    attach.transferTo(targetFile);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "useradd";
                }
                idPicPath = path + File.separator + fileName;
            }
            else
            {
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "useradd";
            }
        }
        // user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        user.setIdPicPath(idPicPath);
        if (1 == 1) // userService.add(user)
        {
            return "redirect:/user/userlist.html";
        }
        return "useradd";
        // return "redirect:userlist.html";
    }
    
    /**
     * save <一句话功能简述> <功能详细描述>
     * 
     * @return
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("useradd.do")
    public String useradd()
        throws Exception
    {
        //
        return "useradd";
    }
    
    @RequestMapping("deluser.do")
    public @ResponseBody String deleteUser(Integer uid)
       
    {
        try
        {
            return userService.deleteUserById(uid);
        }
        catch (Exception e)
        {
            throw new RuntimeException("删除失败");
        }
       
    }
    
    /**
     * 用户管理列表查询 <一句话功能简述> <功能详细描述>
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("userlist.html")
    public String userManager(Model model, @RequestParam(value = "pageIndex", required = false) Integer pageNum,
        @ModelAttribute User user)
    {
        List<Role> roleList = roleService.listRole();
        if (pageNum == null)
        {
            pageNum = 1;
        }
        
        Page page = userService.selectAllUser(pageNum, user.getUserName(), user.getUserRole());
        
        model.addAttribute("roleList", roleList);
        
        model.addAttribute("userList", page.getResult());
        
        model.addAttribute("currentPageNo", page.getPageNum());
        
        model.addAttribute("totalPageCount", page.getPages());
        model.addAttribute("totalCount", page.getTotal());
        
        return "userlist";
    }
    /**
     * 
     * <一句话功能简述>
     * <功能详细描述>
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("logout.do")
    public String logout(HttpSession session)
    {
        session.removeAttribute("userSession");
        return "login";
    }
    
    @ExceptionHandler
    public String hander(HttpServletRequest req,Exception e)
    {

        req.setAttribute("error", e.getMessage());
        return "error";
    }
    
}
